package dht

import (
	"gopkg.in/mgo.v2/bson"
)

type PingResp struct {
	ID ID `bson:"id"`
}

func (dht *DHT) pingHandler(req []byte) ([]byte, error) {
	pr := &PingResp{
		ID: dht.ID(),
	}
	resp, err := bson.Marshal(pr)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (dht *DHT) ping(addr string) (id ID, err error) {
	buf, err := dht.query(addr, PING, []byte("ping"))
	if err != nil {
		return id, err
	}
	pr := &PingResp{}
	err = bson.Unmarshal(buf, &pr)
	if err != nil {
		return id, err
	}
	return pr.ID, nil
}

func (dht *DHT) Ping(addr string) (*Node, error) {
	id, err := dht.ping(addr)
	if err != nil {
		return nil, err
	}
	node := &Node{
		ID:   id,
		Addr: addr,
	}
	return node, nil
}
